package fr.alesia.capital.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import fr.alesia.capital.bean.Partie;
import fr.alesia.capital.bean.Pays;
import fr.alesia.capital.match.PaysFinder;
import fr.alesia.capital.match.PaysFinderUnimatch;

@SuppressWarnings("serial")
public class PartieServlet extends HttpServlet {
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		ServletContext context = this.getServletContext();
		HttpSession session = request.getSession();
		RequestDispatcher dispatcher = null;
		
		String
			terms = request.getParameter("terms"),
			time = request.getParameter("time")
		;
		
		Partie partie = (Partie)session.getAttribute("partie");
		
		if(partie.getPhase() == Partie.DEBUT){
			
			dispatcher = context.getRequestDispatcher("/webapp/page/partie.jsp");
			if(partie.hasNext()){
				partie.next();
			}
		}
		else if(partie.getPhase() == Partie.QUESTION){
			
			if(partie.hasNext()){
				partie.next();
				dispatcher = context.getRequestDispatcher("/webapp/page/partie.jsp");
			}
		}
		else if(partie.getPhase() == Partie.REPONSE){
			
			partie.setMillis(
				partie.getMillis().longValue() +
				Long.valueOf(time).longValue()
			);
			PaysFinder finder = PaysFinderUnimatch.getInstance();
			Pays answer = null;
			
			if(partie.getMode() == Partie.PAYS_CAPITALE){
				
				answer = finder.findByCapitale(terms);
			}
			else if(partie.getMode() == Partie.CAPITALE_PAYS){
				
				answer = finder.findByPays(terms);
			}
			else if(partie.getMode() == Partie.DRAPEAU_PAYS){
				
				answer = finder.findByPays(terms);
			}
			
			if(
				answer != null &&
				answer.equals(partie.getItem())
			){
				partie.addValide(terms);
			}
			else{
				partie.addErreur(terms);
			}
			
			dispatcher = context.getRequestDispatcher("/webapp/page/reponse.jsp");
			
			if(partie.hasNext()){
				partie.next();
			}
		}
		else if(partie.getPhase() == Partie.FIN){
			dispatcher = context.getRequestDispatcher("/webapp/page/resultat.jsp");
		}	
		
		session.setAttribute("partie", partie);
		dispatcher.forward(request, response);
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		this.doPost(request, response);
	}
}
